<template>
  <div class="setting-r-content">
    <div class="search-content">
      <!-- 搜索条 -->
      <Col class="panel search-panel" span="24">
      <Form :model="formHeader" :label-width="20" inline>
        <FormItem>
          <Input v-model="formHeader.name" placeholder="请输入文章标题..." clearable style="width: 200px"></Input>
        </FormItem>
        <FormItem class="margin-l">
          <Button type="primary" style="margin-right: 20px;" @click.native="_queryThing">查询</Button>
          <Button type="primary" @click="_addNew" :disabled="userRole=='ROLE_DEMO'">新增</Button>
        </FormItem>
      </Form>
      </Col>
    </div>
    <div class="w1 setting-scroll__content">
      <Row class="setting-content__row">
        <Col class="panel table-panel" :span="24">
        <Table :columns="columns" :data="tableDatas" border :loading="pageInfo.loading"></Table>
        </Col>
        <!-- 分页 -->
        <Col class="panel page-panel cf" :span="24" style="margin-bottom: 10px;">
        <Page :total="pageInfo.total" :current.sync="pageInfo.current" class="fr" @on-change="switchThePaging"
          :page-size="15"></Page>
        </Col>

        <Col :span="24" class="page-bottom">
        </Col>

        <!-- 新增文章 -->
        <Modal title="新增文章" v-model="dialog.add" :closable="false">
          <div class="w1 h1">
            <Form ref="formAddRef" :label-width="80" :rules="rulesCustom" :model="formAdd">
              <FormItem prop="title" label="标题：">
                <Input type="text" placeholder="文章标题..." v-model.trim="formAdd.title"></Input>
              </FormItem>
              <FormItem prop="newsAbstract" label="摘要：">
                <Input type="text" placeholder="文章摘要..." v-model.trim="formAdd.newsAbstract"></Input>
              </FormItem>
              <FormItem prop="image" label="图片：">
                <div class="demo-upload-list" v-for="item in uploadList">
                  <img :src="item.url">
                  <div class="demo-upload-list-cover">
                    <Icon type="ios-eye-outline" @click.native="handleView(item.name)"></Icon>
                  </div>
                </div>
                <Upload ref="upload" :show-upload-list="false" :before-upload="handleBeforeUpload" type="drag" action="http://192.168.1.90:8081/news/upload"
                  style="display: inline-block;width:58px;">
                  <div style="width: 58px;height:58px;line-height: 58px;">
                    <Icon type="ios-camera" size="20" />
                  </div>
                </Upload>
              </FormItem>
              <FormItem prop="xindex" label="排序：">
                <Input type="text" placeholder="文章排序..." v-model.trim="formAdd.xindex"></Input>
              </FormItem>
              <FormItem prop="url" label="网址：">
                <Input type="text" placeholder="文章地址..." v-model.trim="formAdd.url"></Input>
              </FormItem>
            </Form>
          </div>
          <div slot="footer">
            <Button @click="dialog.add=false">取消</Button>
            <Button type="primary" @click.native="_addArtical">确认</Button>
          </div>
        </Modal>

        <!-- 编辑文章 -->
        <Modal title="编辑文章" v-model="dialog.edit" :closable="false">
          <div class="w1 h1">
            <Form ref="formEditRef" :label-width="80" :rules="rulesCustom" :model="formEdit">
              <FormItem prop="title" label="标题：">
                <Input type="text" placeholder="文章标题..." v-model.trim="formEdit.title"></Input>
              </FormItem>
              <FormItem prop="newsAbstract" label="摘要：">
                <Input type="text" placeholder="文章摘要..." v-model.trim="formEdit.newsAbstract"></Input>
              </FormItem>
              <FormItem prop="image" label="图片：">
                <div class="demo-upload-list" v-for="item in uploadList">
                  <img :src="item.url">
                  <div class="demo-upload-list-cover">
                    <Icon type="ios-eye-outline" @click.native="handleView(item.name)"></Icon>
                  </div>
                </div>
                <Upload ref="upload" :show-upload-list="false" :before-upload="handleBeforeUpload" type="drag" action="http://192.168.1.90:8081/news/upload"
                  style="display: inline-block;width:58px;">
                  <div style="width: 58px;height:58px;line-height: 58px;">
                    <Icon type="ios-camera" size="20" />
                  </div>
                </Upload>
              </FormItem>
              <FormItem prop="xindex" label="排序：">
                <Input type="text" placeholder="文章排序..." v-model.trim="formEdit.xindex"></Input>
              </FormItem>
              <FormItem prop="url" label="网址：">
                <Input type="text" placeholder="文章地址..." v-model.trim="formEdit.url"></Input>
              </FormItem>
            </Form>
          </div>
          <div slot="footer">
            <Button @click="dialog.edit=false">取消</Button>
            <Button type="primary" @click.native="_editArtical">确认</Button>
          </div>
        </Modal>

        <Modal title="查看大图" v-model="dialog.img" :closable="false">
          <div style="height:300px;width:300px;margin:0 auto;">
            <img :src="selectImg" style="width:100%;height:100%;">
          </div>
          <div slot="footer">
            <Button @click="dialog.img=false">取消</Button>
          </div>
        </Modal>
      </Row>
    </div>
  </div>
</template>
<script>
  import {
    uploadImage,
    addArtical,
    deleteArtical,
    editArtical,
    getArical
  } from '@/api';
  import {
    mapGetters,
    mapState
  } from 'vuex';

  import {
    validateDeviceId,
    validateTitle
  } from '@/utils/rules'
  export default {
    computed: {
      ...mapGetters(['userInfo']),
      ...mapState({
        userRole: state => state.userInfo.rname
      })
    },
    mounted() {
      this._getArical();
    },
    data() {
      return {
        addNewDisabled: false,
        formHeader: {
          name: ""
        },
        selectImg: "",
        editCover: "",
        formAdd: {
          title: "",
          newsAbstract: "",
          cover: '',
          xindex: null,
          url: "",
          userId: "",
        },
        formEdit: {
          title: "",
          newsAbstract: "",
          xindex: 0,
          url: "",
          userId: "",
        },
        pageInfo: {
          current: 1,
          page: 1,
          total: 0,
          loading: false
        },
        dialog: {
          add: false,
          edit: false,
          img: false
        },
        uploadList: [],
        columns: [{
          title: "排名",
          key: "xindex",
          align: "center"
        }, {
          title: "标题",
          key: "title",
          align: "center"
        }, {
          title: "摘要",
          key: "newsAbstract",
          align: "center"
        }, {
          title: "图片",
          align: "center",
          render: (h, params) => {
            const row = { ...params.row
            };
            return h('div', {
              class: ['demo-upload-list']
            }, [
              h('img', {
                attrs: {
                  src: row.cover
                }
              }), h('div', {
                class: ['demo-upload-list-cover']
              }, [
                h('Icon', {
                  props: {
                    type: 'ios-eye-outline'
                  },
                  on: {
                    click: () => {
                      this.selectImg = row.cover;
                      this.dialog.img = true;
                    }
                  }
                })
              ])
            ])
          }
        }, {
          title: "公众号网址",
          key: "url",
          align: "center"
        }, {
          title: "创建时间",
          align: "center",
          render: (h, params) => {
            const createdAt = params.row.createdAt;
            const _t = this;
            return h('span', _t.filterTime(createdAt))
          }
        }, {
          title: "更新时间",
          align: "center",
          render: (h, params) => {
            const _t = this;
            const updatedAt = params.row.updatedAt;
            return h('span', _t.filterTime(updatedAt))
          }
        }, {
          title: "操作",
          align: "center",
          render: (h, params) => {
            const _t = this;
            const row = { ...params.row
            }
            return h('div', [
              h('Button', {
                props: {
                  type: "primary",
                  size: "small",
                  disabled: _t.userRole == "ROLE_DEMO"
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    _t.handleEdit(row)
                  }
                }
              }, '编辑'),
              h('Poptip', {
                props: {
                  confirm: true,
                  title: '您确定要删除这条数据吗?',
                  transfer: true,
                  cancelText: "取消"
                },
                on: {
                  'on-ok': () => {
                    _t.handleDelete(row);
                  }
                }
              }, [
                h('Button', {
                  props: {
                    type: 'error',
                    size: 'small',
                    disabled: _t.userRole == "ROLE_DEMO"
                  }
                }, '删除')
              ])
            ])
          }
        }],
        tableDatas: [],
        rulesCustom: {
          title: [{
            required: true,
            trigger: "blur",
            validator: validateTitle('标题')
          }],
          newsAbstract: [{
            required: true,
            trigger: "blur",
            validator: validateTitle('摘要')
          }],
          xindex: [{
            required: true,
            validator: validateDeviceId('排序', '排序只能输入正整数'),
            trigger: "blur"
          }],
          url: [{
            required: true,
            message: "请输入文章地址",
            trigger: "blur"
          }]
        }
      }
    },
    methods: {
      filterTime(time) {
        return this.moment(time).format('YYYY-MM-DD')
      },

      switchThePaging(index) {
        this.pageInfo.page = index;
        this._getArical();
      },
      _queryThing() {
        let vm = this;
        vm.pageInfo.current = 1;
        vm.pageInfo.page = 1;
        vm._getArical();
      },
      _addNew() {
        this.dialog.add = true;
        this.uploadList = [];
        this.$nextTick(_ => {
          this.$refs.formAddRef.resetFields();
          this.formAdd.cover = '';
        });
      },

      // 编辑
      handleEdit(row) {
        const _t = this;
        _t.dialog.edit = true;
        this.$nextTick(_ => {
          this.$refs.formEditRef.resetFields();
          _t.formEdit = { ...row
          };
          if (row.cover == "") {
            _t.uploadList = []
          } else {
            _t.uploadList = [{
              url: row.cover,
              name: ""
            }]
          }
        });
      },


      // 预览图片
      handleView(url) {

      },

      // 上传图片
      handleBeforeUpload(file) {
        let _t = this;
        if (file.type.startsWith('image/')) {
          let reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = function (e) {
            let str = e.target.result;
            uploadImage({
              imageBase64: str
            }).then(res => {
              _t.uploadList = [{
                name: "",
                url: res.data
              }];
              if (_t.dialog.add == true) {
                _t.formAdd.cover = res.data;
              } else if (_t.dialog.edit == true) {
                // _t.formEdit.cover = res.data;
                _t.editCover = res.data
              }
            })
          };
        } else {
          this.$Message.error('图片格式不正确!!');
        }
        return false
      },


      // 获取文章列表
      _getArical() {
        let _t = this;
        const params = {
          title: this.formHeader.name,
          page: this.pageInfo.page,
          size: 15
        }
        _t.pageInfo.loading = true;
        getArical(params).then(res => {
          if (res.code == 200) {
            this.tableDatas = res.data.list;
            this.pageInfo.total = res.data.total;
            setTimeout(() => {
              _t.pageInfo.loading = false;
            }, 500)
          }
        })
      },

      // 确认新增文章
      _addArtical() {
        let _t = this;
        _t.$refs.formAddRef.validate(valid => {
          if (valid) {
            if (!_t.formAdd.cover) {
              this.$Message.error('请选择图片！！');
              return false
            }
            this.addNewDisabled = true;
            let params = Object.assign({}, _t.formAdd, {
              userId: _t.userInfo.id,
            });
            addArtical(params).then(res => {
              if (res.code == 200) {
                _t.$Message.success('新增成功');
                this.addNewDisabled = false;

                _t.dialog.add = false;
                _t._getArical();
              } else {
                this.addNewDisabled = false;
                _t.$Message.error(res.message);
              }
            })
          }
        })
      },

      // 确认更新文章
      _editArtical() {
        let _t = this;
        _t.$refs.formEditRef.validate(valid => {
          if (valid) {
            let params = { ..._t.formEdit
            };
            params.cover = _t.editCover;
            editArtical(params).then(res => {
              if (res.code == 200) {
                _t.$Message.success('操作成功');
                _t.dialog.edit = false;
                _t._getArical();
              }
            })
          }
        })

      },

      // 确认删除
      handleDelete(row) {
        let params = row.id;
        let _t = this;
        deleteArtical(params).then(res => {
          if (res.code == 200) {
            _t.$Message.success('操作成功');
            _t._getArical();
          }
        })
      }
    }
  }

</script>
